<template>
  <div class="model-manage">
    <div class="setting-content">
      <!-- <h2 class="setting-header">
        <strong>资源管理</strong>
      </h2>-->

      <div class="list-content">
        <!-- 添加左侧筛选树 -->
        <div class="filter-sidebar" v-loading="modelListLoading">
          <!-- <div class="filter-group filter-group1">
            <div class="filter-title" >
              <div class="title-left" @click="handlePrefixClick()">
                <i class="iconfont">&#xe6e3;</i>
                <span>全部</span>
              </div>
              <i class="iconfont arrow-icon" @click="handleClickMine" :class="{ 'is-expand': isMyFileExpand }">&#xe645;</i>
            </div>
            <ul class="filter-list" v-show="isMyFileExpand">
              <li
                v-for="(model, index) in modelList"
                :key="model.id"
                class="filter-item"
                :class="{ 
                  active: modelForm.modelId === model.id,
                  'model-line': index == 2
                }"
                @click="handleModelNodeClick(model)"
              >
                <span class="model-name">{{ model.name }}</span>
              </li>
            </ul>
          </div> -->
          
          <div class="filter-group">
            <el-select
              v-model="modelForm.modelId"
              placeholder="请选择模型"
              class="model-select"
              @change="handleModelNodeClick"
            >
              <el-option
                v-for="model in allModelList"
                :key="model.id"
                :label="model.name"
                :value="model.id"
              />
            </el-select>
          </div>
          <!-- 第一层文件夹 快捷访问 -->
          <div class="filter-group">
            <div class="filter-title" @click="handleClickShortcut">
              <div class="title-left">
                <i class="iconfont">&#xe6e2;</i>
                <span>文件夹</span>
              </div>
              <i class="iconfont arrow-icon" :class="{ 'is-expand': isFirstFolderExpand }">&#xe645;</i>
            </div>
            <el-scrollbar max-height="400px">
              <ul class="filter-list" v-show="isFirstFolderExpand">
                <li
                  v-for="item in firstFolderList"
                  :key="item.id"
                  class="filter-item"
                  :class="{ 
                    active: curFolder?.id === item.id,
                  }"
                  @click="handleFirstFolderClick(item)"
                >
                  <div class="file-item">
                    <img class="file-img" :src="require(`@/assets/sourceManage/folder.svg`)" alt />
                    <span class="shortcut-name">{{ item.name }}</span>
                  </div>
                </li>
                <li v-if="!firstFolderList.length" class="filter-item empty-tip">
                  <span>暂无快文件夹</span>
                </li>
              </ul>
            </el-scrollbar>
          </div>

          <el-divider />
          <!-- 自定义快捷访问 -->
          <div class="filter-group">
            <div class="filter-title" @click="handleClickShortcut">
              <div class="title-left">
                <i class="iconfont">&#xe6f4;</i>
                <span>快捷访问</span>
              </div>
              <i class="iconfont arrow-icon" :class="{ 'is-expand': isShortcutExpand }">&#xe645;</i>
            </div>
            <el-scrollbar max-height="400px">
              <ul class="filter-list" v-show="isShortcutExpand">
                <li
                  v-for="item in shortcutList"
                  :key="item.id"
                  class="filter-item"
                  :class="{ 
                    active: curFolder?.id === item.folderId,
                  }"
                  @click="handleShortcutClick(item)"
                >
                  <div class="file-item">
                    <img class="file-img" :src="require(`@/assets/sourceManage/folder.svg`)" alt />
                    <span class="shortcut-name">{{ item.folderName }}</span>
                  </div>
                  <el-dropdown>
                    <span class="el-dropdown-link unmover">
                      <i class="iconfont option-icon">&#xe78d;</i>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click.stop="handleDeleteShortcut(item)">取消快捷访问</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </li>
                <li v-if="!shortcutList.length" class="filter-item empty-tip">
                  <span>暂无快捷访问</span>
                </li>
              </ul>
            </el-scrollbar>
          </div>
        </div>

        <!-- 原有的文件列表区域 -->
        <div class="file-list-container">
          <div class="header-option">
            <el-button v-permission="['build:model:model:add'] || true" type="primary" @click="handleAddFolder">新建文件夹</el-button>
            <el-button v-permission="['build:model:model:add'] || true" type="primary" @click="handleAddFile">
              新建资源
              <span v-if="modelForm.modelId">（{{toShowType(modelForm.modelId)}}）</span>
            </el-button>
            <el-button type="danger" v-show="fileSelectionList.length" @click="handleBatchDelete()">批量放入回收站</el-button>
          </div>
          <!-- 文件路径 -->
          <el-page-header :title="'上一级'" @back="goBack" style="margin-bottom: 10px;">
            <template #content>
              <el-breadcrumb separator="/">
                <el-breadcrumb-item @click="handlePrefixClick()">
                  <span class="file-path">根目录</span>
                </el-breadcrumb-item>
                <el-breadcrumb-item v-for="(item, index) in prefix" :key="index" @click="handlePrefixClick(item)">
                  <span class="file-path">{{ item.name }}</span>
                </el-breadcrumb-item>
              </el-breadcrumb>
            </template>
          </el-page-header>
          <!-- 文件列表 -->
          <RuifoxTable
            :loading="curFileListLoading"
            :default-index="false"
            :default-checkbox="true"
            v-model:tableData="curFileList"
            v-model:fieldList="fieldList"
          >
            <!-- 多选 -->
            <template #default-checkbox='{element}'>
              <div class="table-div-check">
                <el-checkbox class="unmover" v-model="element.checked" @change="handleSelectionChange(element)" size=""/>
              </div>
            </template>
            <template #name='{element}'>
              <div class="file-item-box">
                <div class="file-item">
                  <div class="thumb-box" v-if="element.modelId == 1">
                    <img class="thumb-img" :src="element.resourceData?.url" alt />
                  </div>
                  <img class="file-img" v-else :src="element.fileExt" alt />
                  <span v-if="!element.modelId" class="file-name" @click="handleFileClick(element)">{{ element.name }}</span>
                  <span v-else class="file-name" @click="handleUpdateFile(element)">{{ element.resourceData.title }}</span>
                </div>
              </div>
            </template>
            <template #update_time='{element}'>
              <span v-if="!element.modelId">
                <span v-if="element.update_time">{{ formatDate(element.update_time, 'yyyy-MM-dd HH:mm:ss') }}</span>
                <span v-else>-</span>
              </span>
              <span v-else>
                <span v-if="element.resourceData.update_time">{{ formatDate(element.resourceData.update_time, 'yyyy-MM-dd HH:mm:ss') }}</span>
                <span v-else>-</span>
              </span>
            </template>
            <template #modelId='{element}'>
              <span>{{ toShowType(element.modelId) }}</span>
            </template>
            <template #options='{element}'>
              <div class="table-td-option unmover">
                <el-button type="primary" v-if="element.modelId <= 3 " link @click="handleDownload(element)" >下载</el-button>
                <el-button type="primary" v-if="!element.modelId" link @click="handleUpdateFolder(element)" >重命名</el-button>
                <el-button type="primary" v-else link @click="handleFileClick(element)" >查看</el-button>
                <el-dropdown>
                  <span class="el-dropdown-link unmover">
                    <i class="iconfont">&#xe78d;</i>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <template v-if="!element.modelId">
                        <el-dropdown-item v-if="shortcutList.find(item => item.folderId == element.id)" @click="handleDeleteShortcut2(element)">取消快捷访问</el-dropdown-item>
                        <el-dropdown-item v-else @click="handleAddShortcut(element)">添加到快捷访问</el-dropdown-item>
                      </template>
                      <el-dropdown-item @click="handleMove(element)">移动</el-dropdown-item>
                      <el-dropdown-item @click="handleBatchDelete(element)">放入回收站</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </RuifoxTable>
          <PaginationView
            :total="queryData.total"
            :pageSize="queryData.pageSize"
            :currentPage="queryData.currentPage"
            @changeSize="handleSizeChange"
            @currentChange="handleCurrentChange"
            @refreshList="handleSearch"
          />
        </div>
      </div>
    </div>
    <!-- 新增/重命名文件夹 -->
    <el-dialog v-model="folderDialog" :title="'文件夹'" width="700px">
      <el-form :model="folderForm" ref="folderFormRef" :rules="folderRules" label-width="auto" style="max-width: 600px">
        <el-form-item label="文件夹名称" prop="name">
          <el-input v-model="folderForm.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="folderDialog = false">取消</el-button>
          <el-button type="primary" :loading="folderDialogLoading" @click="handleAddFolderSubmit(folderFormRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改选择模型弹窗 -->
    <el-dialog v-model="modelDialog" title="选择模型" width="800px">
      <div class="model-list">
        <div v-for="item in modelList" :key="item.id" class="model-item" :class="{ active: modelForm.modelId === item.id }" @click="handleSelectModel(item)">
          <div class="model-icon">
            <img :src="getAvatarUrl(item.id)" alt />
          </div>
          <div class="model-name">{{ item.name }}</div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="modelDialog = false">取消</el-button>
          <el-button type="primary" :disabled="!modelForm.modelId" @click="handleModelSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 图片、文件 上传弹窗 -->
    <el-dialog v-model="resourceDialog" title="文件上传" width="700px">
      <el-form :model="resourceForm" ref="resourceFormRef" :rules="resourceRules" label-width="auto" style="max-width: 600px">
        <el-form-item label="文件名称" prop="title">
          <el-input v-model="resourceForm.title" placeholder="上传后自动填充或手动输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resourceDialog = false">取消</el-button>
          <el-button type="primary" :loading="resourceDialogLoading" @click="handleAddResourceSubmit(resourceFormRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 全部文件夹弹窗 移动时使用 -->
    <el-dialog v-model="moveDialog" title="移动到" width="700px">
      <FolderList v-if="moveDialog" ref="folderListRef" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="moveDialog = false">取消</el-button>
          <el-button type="primary" :loading="moveDialogLoading" @click="handleMoveSubmit(resourceFormRef)">移动到此</el-button>
        </div>
      </template>
    </el-dialog>
    <FilesUpload v-if="showFilesUpload" v-model:showDialog="showFilesUpload" :bucketGroupId="999" :isPublic="false" @getFileList="insertFiles" :isToJpg="false"></FilesUpload>
    <el-drawer v-model="showPreview" title="" size="700px">
      <ResourcePreview v-if="showPreview" :curShare="curShare" />
    </el-drawer>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { FilesUpload, ResourcePreview } from '@ruifox-cms/components'
import { folderCreate, selectPageFolderAndResourceById, deleteListFolderAndResource, folderUpdate } from '@/api/folder'
import { folderResourceInsertList, folderResourceUpdate, folderResourceSelectHome } from '@/api/folderResource'
import { getModelList } from '@/api/model'
import { ElMessageBox, ElMessage } from 'element-plus'
// import { download } from '@/utils/tools'
import { useRouter } from 'vue-router'
import { shortcutSelectAll, shortcutCreate, shortcutDeleteList, moveListFolderAndResource } from '@/api/folder'
import FolderList from './components/FolderList.vue'
import { formatDate } from '@/utils/tools'

const router = useRouter()
const curFileList = ref([])
const curFileListLoading = ref(false)
const curFolder = ref(null)

const defaultQueryData = {
  currentPage: 1,
  pageSize: 15,
  total: 0,
  id: 0, //文件or文件夹id
}
const fieldList = ref([
  {
    title: '名称',
    name: 'name',
    showTextTip: true,
    width: 400
  },
  {
    title: '修改时间',
    name: 'update_time',
  },
  {
    title: '类型',
    name: 'modelId',
  },
  {
    title: '操作',
    width: 180,
    fixed: 'right',
    name: 'options'
  }
])
// 第一层文件夹
const firstFolderList = ref([])
const firstFolderListLoading = ref(false)
const isFirstFolderExpand = ref([])
const getFirstFolderList = async () => {
  firstFolderListLoading.value = true
  let params = {
    currentPage: 1,
    pageSize: 9999,
    id: 0, //文件or文件夹id
  }
  const res = await selectPageFolderAndResourceById(params).finally(() => {
    firstFolderListLoading.value = false
  })
  firstFolderList.value = res.data.folderDtoList.map((item) => {
    return {
      ...item,
      fileExt: getAvatarUrl(item.modelId),
    }
  })
}
const queryData = ref(structuredClone(defaultQueryData))
const getCurFileList = async () => {
  curFileListLoading.value = true
  queryData.value.id = curFolder.value?.id || 0
  const res = await selectPageFolderAndResourceById(queryData.value).finally(() => {
    curFileListLoading.value = false
  })
  curFileList.value = [...res.data.folderDtoList, ...res.data.folderResourceDtoList].map((item) => {
    return {
      ...item,
      fileExt: getAvatarUrl(item.modelId),
    }
  })
  queryData.value.total = res.data.total
}
const showPreview = ref(false)
const curShare = ref({})
// 文件路径(面包屑)
const prefix = ref([])
// 点击文件/文件夹
const handleFileClick = async (val) => {
  if (!val.modelId) {
    //点击文件夹
    curFolder.value = val
    prefix.value.push(val)
    getCurFileList()
  } else {
    //点击文件
    // getCurFileList()
    curShare.value = val
    showPreview.value = true
  }
}
// 点击路径面包屑
const handlePrefixClick = (val) => {
  curFolder.value = val
  if (!val) {
    prefix.value = []
    modelForm.value = ref(structuredClone(modelDefaultForm))
    getCurFileList()
  } else if (val.name == prefix.value[prefix.value.length - 1].name) {
    //点击本级
    getCurFileList()
  } else {
    //点击路径
    let curIndex = prefix.value.findIndex((item) => item.name == val.name)
    prefix.value = prefix.value.slice(0, curIndex + 1)
    getCurFileList()
  }
}
// 多选
const fileSelectionList = ref([])
const handleSelectionChange = (val) => {
  if(fileSelectionList.value.find(item => item.id == val.id)){
    fileSelectionList.value.splice(fileSelectionList.value.indexOf(val.id),1)
  }else{
    fileSelectionList.value.push(val)
  }
  if(process.env.NODE_ENV === 'development') console.log(fileSelectionList.value)
}
const handleSizeChange = (size) => {
  queryData.value.pageSize = size
  handleSearch()
}
const handleCurrentChange = (page) => {
  queryData.value.currentPage = page
  handleSearch()
}
/*********************** 新建文件夹 开始 ************************/
const folderDialog = ref(false)
const folderDialogLoading = ref(false)
const defaultFolderForm = {
  name: '',
  pid: 0,
}
const folderForm = ref(structuredClone(defaultFolderForm))
const folderFormRef = ref(null)
const folderRules = ref({
  name: [{ required: true, message: '请输入文件夹名称', trigger: 'blur' }],
})
const handleAddFolder = async () => {
  folderForm.value = structuredClone(defaultFolderForm)
  folderForm.value.pid = curFolder.value?.id || 0
  folderDialog.value = true
}
// 修改文件夹
const handleUpdateFolder = async (row) => {
  folderForm.value = structuredClone(row)
  folderForm.value.pid = curFolder.value?.id || 0
  folderDialog.value = true
}
const handleAddFolderSubmit = async () => {
  await folderFormRef.value.validate()
  folderDialogLoading.value = true
  let res = null
  if (folderForm.value.id) {
    // 修改
    res = await folderUpdate(folderForm.value).finally(() => {
      handleSearch()
      folderDialogLoading.value = false
    })
  } else {
    // 新增
    res = await folderCreate(folderForm.value).finally(() => {
      handleSearch()
      folderDialogLoading.value = false
    })
  }
  if (res.code == 20000) {
    folderDialog.value = false
  } else {
    ElMessage.error(res.msg)
  }
}
/*********************** 新建文件夹 结束 ************************/
/*********************** 新建文件 开始 ************************/
const curFile = ref(null)
const addType = ref('文件夹中添加')

const handleAddFile = () => {
  curFile.value = null
  modelForm.value.dataId = null
  if (modelForm.value?.modelId) {
    //如果当前有模型，直接打开弹窗
    handleModelSubmit()
    //在模型条件下，添加文件，无层级
    addType.value = '模型条件中添加'
  } else {
    modelDialog.value = true
    //在文件夹中，添加文件，有层级
    addType.value = '文件夹中添加'
  }
}

const modelDialog = ref(false)
const modelDefaultForm = {
  modelId: null, //模型id
  dataId: null, //文件id
  type: null, //资源类型
}
const modelForm = ref(structuredClone(modelDefaultForm))
// 文件上传弹窗
const resourceDialog = ref(false)
const resourceDialogLoading = ref(false)
const defaultResourceForm = {
  title: '',
  url: '',
}
const tagList = ref([])
const resourceFormList = ref([])
const resourceForm = ref(structuredClone(defaultResourceForm))
const resourceFormRef = ref(null)
const resourceRules = ref({
  // title: [{ required: true, message: '请输入文件名称', trigger: 'blur' }],
  url: [{ required: true, message: '请上传文件', trigger: 'blur' }],
})
// 跳转资源发布页
const handleModelSubmit = async () => {
  try {
    if (!modelForm.value.modelId) {
      ElMessage.error('请选择模型')
      return
    }
    if (modelForm.value.type == 0) {
      //数据资源，如图片1、视频2、文件3
      resourceForm.value = structuredClone(defaultResourceForm)
      resourceFormList.value = []
      if (curFile.value?.id) {
        //编辑
        resourceForm.value.title = curFile.value.resourceData.title
        resourceForm.value.url = curFile.value.resourceData.url
        resourceForm.value.tagList = curFile.value.resourceData.tagList
      }
      showFilesUpload.value = true
    } else if (modelForm.value.type == 1) {
      //栏目资源，如文章、医生
      let url = router.resolve({
        path: '/resource/manage/setting',
        query: {
          modelId: modelForm.value.modelId,
          folderId: curFolder.value?.id || 0,
          dataId: modelForm.value.dataId,
          publishType: modelForm.value.publishType, //1:文章/单页, 0:非文章
        },
      })
      window.open(url.href, '_blank')
    }
    modelDialog.value = false
  } catch (error) {
    console.log('表单验证失败')
  }
}

// 附件上传
const showFilesUpload = ref(false)
const insertFiles = (filesList) => {
  console.log('filesList', filesList)
  resourceFormList.value = filesList.map((item) => {
    return {
      resourceData: {
        title: item.name,
        url: item.url,
        tagList: item.resourceData?.tagList || [],
      },
      needUpload: item.needUpload,
    }
  })
  handleAddResourceSubmit()
}
// 编辑文件
const handleUpdateFile = async (row) => {
  curFile.value = row
  let model = modelList.value.find((item) => item.id == row.modelId)
  modelForm.value.type = model.type
  modelForm.value.modelId = row.modelId
  modelForm.value.dataId = row.id
  modelForm.value.publishType = model.publishType
  if (modelForm.value.type == 1) {
    handleModelSubmit()
  } else {
    resourceForm.value = structuredClone(row.resourceData)
    resourceFormList.value = [structuredClone(row.resourceData)]
    tagList.value = row.resourceData.tagList ? structuredClone(JSON.parse(row.resourceData.tagList)) : []
    resourceDialog.value = true
  }
}
// 新建/编辑文件确定
const submitImgLoading = ref(false)
const handleAddResourceSubmit = async () => {
  const formData = {}
  try {
    submitImgLoading.value = true
    let res = null
    if (curFile.value?.id) {
      //编辑文件
      formData.id = curFile.value.id
      formData.modelId = modelForm.value.modelId
      formData.resourceData = resourceForm.value
      formData.resourceId = curFile.value.resourceData.id
      res = await folderResourceUpdate(formData)
    } else {
      //新增文件
      formData.folderId = curFolder.value?.id || 0
      formData.modelId = modelForm.value.modelId
      formData.resourceDataList = resourceFormList.value
      res = await folderResourceInsertList(formData)
    }
    submitImgLoading.value = false
    if (res.code === 20000) {
      ElMessage.success('上传成功')
      if (addType.value == '文件夹中添加') {
        getCurFileList()
      } else {
        handleModelNodeClick(modelForm.value.modelId)
      }
      resourceDialog.value = false
    }
  } catch (e) {
    console.log('新增/编辑文件失败', e)
    submitImgLoading.value = false
  }
}

/*********************** 新建文件 结束 ************************/

// 模型类型列表
const modelList = ref([])
const allModelList = ref([])
const modelListLoading = ref(false)
const getModelListAsync = async () => {
  modelListLoading.value = true
  let res = await getModelList({type: 1}).finally(() => {
    modelListLoading.value = false
  })
  if (res.code === 20000) {
    allModelList.value = [{id: 0, name: '全部', type: 0, publishType: 0}, ...res.data]
    modelList.value = res.data
  }
}
getModelListAsync()
// 反显文件类型
const toShowType = (modelId) => {
  let obj = modelList.value.find((item) => item.id == modelId)
  return obj ? obj.name : '-'
}

// 返回上一级
const goBack = () => {
  if (prefix.value.length > 0) {
    let lastFolder = prefix.value[prefix.value.length - 2]
    if (lastFolder) {
      curFolder.value = lastFolder
      prefix.value.pop()
    } else {
      curFolder.value = null
      prefix.value = []
    }
    getCurFileList()
  }
}

// 文件图标
const getAvatarUrl = (type) => {
  if (type) {
    try {
      // return require(`@/assets/sourceManage/${type}.svg`)
      return require(`@/assets/sourceManage/9.svg`)
    } catch (e) {
      return require(`@/assets/sourceManage/9.svg`)
    }
  } else {
    return require(`@/assets/sourceManage/folder.svg`)
  }
}

// 批量删除
const handleBatchDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要将选中的文件/文件夹放入回收站吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const params = {
      folderIdList: [],
      pid: curFolder.value?.id || 0,
      resourceIdList: [],
    }

    if (row) {
      if (row.modelId) {
        // 资源文件
        params.resourceIdList.push(row.id)
      } else {
        // 文件夹
        params.folderIdList.push(row.id)
      }
    } else {
      // 区分文件夹和资源文件
      fileSelectionList.value.forEach((item) => {
        if (item.modelId) {
          // 资源文件
          params.resourceIdList.push(item.id)
        } else {
          // 文件夹
          params.folderIdList.push(item.id)
        }
      })
    }
    const res = await deleteListFolderAndResource(params)
    if (res.code === 20000) {
      ElMessage.success('操作成功')
      handleSearch()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.log('取消操作')
  }
}
// 移动
const folderListRef = ref(null)
const moveDialog = ref(false)
const moveDialogLoading = ref(false)
const handleMove = (row) => {
  curFile.value = row
  moveDialog.value = true
}

// 移动 提交
const handleMoveSubmit = async () => {
  moveDialog.value = false
  if (folderListRef.value) {
    let params = {
      fodlerResourceIdList: [],
      folderIdList: [],
      pid: folderListRef.value.moveQueryData.pid,
    }
    if (curFile.value.modelId) {
      params.fodlerResourceIdList.push(curFile.value.id)
    } else {
      params.folderIdList.push(curFile.value.id)
    }
    const res = await moveListFolderAndResource(params)
    if (res.code === 20000) {
      ElMessage.success('移动成功')
      getCurFileList()
    }
  }
}
// 添加到快捷访问
const shortcutList = ref([])
const getShortcutList = async () => {
  const res = await shortcutSelectAll()
  if (res.code === 20000) {
    shortcutList.value = res.data
  }
}

const handleAddShortcut = async (row) => {
  try {
    if (row.modelId) {
      return
    }
    const data = {
      folderId: row.modelId ? undefined : row.id, // 文件夹id
    }
    const res = await shortcutCreate(data)
    if (res.code === 20000) {
      getShortcutList() // 刷新快捷访问列表
    } else {
      ElMessage.error(res.msg || '添加失败')
    }
  } catch (error) {
    console.log('添加快捷访问失败', error)
  }
}

// 取消快捷访问
const handleDeleteShortcut = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该快捷访问吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const res = await shortcutDeleteList({
      idList: [row.id],
    })
    if (res.code === 20000) {
      getShortcutList() // 刷新快捷访问列表
    } else {
      ElMessage.error(res.msg || '取消失败')
    }
  } catch (error) {
    console.log('取消快捷访问失败', error)
  }
}

// 取消快捷访问2
const handleDeleteShortcut2 = async (row) => {
  let obj = shortcutList.value.find((item) => item.folderId == row.id)
  handleDeleteShortcut(obj)
}

const handleShortcutClick = (item) => {
  curFolder.value = {
    id: item.folderId,
    name: item.folderName,
  }
  prefix.value = [curFolder.value]
  getCurFileList()
}

const handleFirstFolderClick = (item) => {
  curFolder.value = {
    id: item.id,
    name: item.name,
  }
  getCurFileList()
}

const handleSelectModel = (model) => {
  modelForm.value = model
  modelForm.value.modelId = model.id
}

const defaultModelQueryData = {
  total: 0,
  modelIdList: null, //模型id
}
const modelQueryData = ref(structuredClone(defaultModelQueryData))
// 处理节点点击
const handleModelNodeClick = (val) => {
  let data = allModelList.value.find(item => item.id == val)
  modelForm.value.modelId = (data.id || data.id == 0)? data.id : data.modelId
  modelForm.value.type = data.type
  modelForm.value.publishType = data.publishType
  folderResourceSelectGreatAsync()
}
//根据模型id查资源
const folderResourceSelectGreatAsync = async () => {
  prefix.value = []
  curFileListLoading.value = true
  modelQueryData.value.modelIdList = modelForm.value.modelId === 0 ? undefined : modelForm.value.modelId
  let params = {
    ...modelQueryData.value,
    currentPage: queryData.value.currentPage,
    pageSize: queryData.value.pageSize,
  }
  const res = await folderResourceSelectHome(params).finally(() => {
    curFileListLoading.value = false
  })
  curFileList.value = res.data.list.map((item) => {
    return {
      ...item,
      fileExt: getAvatarUrl(item.modelId),
    }
  })
  queryData.value.total = res.data.total
}
// 添加展开收起状态
// const isMyFileExpand = ref(true)
const isShortcutExpand = ref(true)

// 修改点击处理函数
// const handleClickMine = () => {
//   isMyFileExpand.value = !isMyFileExpand.value
// }
const handleClickShortcut = () => {
  isShortcutExpand.value = !isShortcutExpand.value
}

const handleSearch = () => {
  console.log('handleSearchmodelForm.value',modelForm.value)
  if (modelForm.value?.modelId || modelForm.value.modelId == 0) {
    handleModelNodeClick(modelForm.value.modelId)
  } else {
    getCurFileList()
  }
  getFirstFolderList()
}
onMounted(() => {
  handleSearch()
  getShortcutList() // 获取快捷访问列表
  window['updatePage'] = val => {
    ElMessage({
      showClose: true,
      message: val,
      type: 'success'
    })
    handleSearch()
  }
})
</script>
<style scoped lang="scss">
.model-manage {
  .header-option {
    margin-bottom: 10px;
  }
  .file-path {
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
  }
  .list-content {
    display: flex;
    gap: 20px;

    .filter-sidebar {
      width: 200px;
      background: #fff;
      border-radius: 4px;
      padding: 0 16px;
      border-right: 1px #eee solid;
      flex-shrink: 0;

      .model-select {
        width: 100%;
      }

      .filter-group {
        margin-bottom: 12px;

        .filter-title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          cursor: pointer;
          margin: 8px;
          font-size: 14px;
          color: #333;
          font-weight: 600;
          i {
            margin-right: 4px;
          }
          .arrow-icon {
            transition: all 0.3s;
            font-weight: 500;
            font-size: 10px;
            &.is-expand {
              transform: rotate(90deg);
            }
          }
        }

        .filter-list {
          padding-left: 0px;
          .filter-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px;
            cursor: pointer;
            transition: all 0.3s;
            color: #666;
            .option-icon {
              visibility: hidden;
            }
            &:hover {
              background-color: #f5f7fa;
              .option-icon {
                visibility: visible;
              }
            }

            &.active {
              background-color: #ecf5ff;
              color: $mainColor;
            }

            .model-name {
              font-size: 14px;
              padding-left: 20px;
            }
            .file-item {
              display: flex;
              align-items: center;
              .file-img {
                width: 18px !important;
                height: 18px !important;
                margin-right: 5px;
              }
            }
          }
          .model-line {
            border-bottom: 1px solid #666;
          }
        }
      }
      .filter-group1 {
      }
    }

    .file-list-container {
      flex: 1;
      .hide-prefix {
        visibility: hidden;
      }
 
      .file-item-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .file-item {
          display: flex;
          align-items: center;
          .thumb-box {
            width: 20px;
            height: 20px;
            margin-right: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            .thumb-img {
              max-width: 100%;
              max-height: 100%;
            }
          }
          .file-name {
            cursor: pointer;
          }
          .file-img {
            width: 18px !important;
            height: 18px !important;
            margin-right: 10px;
          }
        }
        &:hover {
          .operation-buttons {
            display: flex !important;
          }
          .file-name {
            text-decoration: underline;
          }
        }
      }
    }
  }
  .operation-buttons {
    flex-shrink: 0;
    padding-left: 20px;
    display: none;
    align-items: center;
    .el-dropdown-link {
      color: $mainColor;
      padding: 0 10px;
      cursor: pointer;
      .iconfont {
        font-size: 14px;
        margin-top: 2px;
      }
    }
  }

  .model-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 20px;
    padding: 20px;

    .model-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        border-color: $mainColor;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      }

      &.active {
        border-color: $mainColor;
        background-color: #f5f7fa;
      }

      .model-icon {
        width: 40px;
        height: 40px;
        margin-bottom: 10px;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .model-name {
        font-size: 14px;
        color: #606266;
        text-align: center;
      }
    }
  }
}

::v-deep(.choose-check-box) {
  display: none !important;
}
</style>
